<template>
  <TopNavBar :title="_t18('17_transfer1')" type="back" />

  <div class="transfer-apply-container">
    <div class="transfer-card">
      <div class="transfer-row">
        <img class="account-icon" :src="transferOutAccountList?.icon" />
        <span class="account-title">{{ transferOutAccountList?.text }}</span>
        <span class="account-balance">{{ _t18('17_transfer2') }}: {{ transgerOutAmont && transgerOutAmont.amout || 0 }}</span>
      </div>
      <div class="transfer-input-row">
        <input class="transfer-input" v-model="params.amount" :placeholder="_t18('17_transfer3')" />
        <button class="all-btn" @click="setAll">{{ _t18('17_transfer4') }}</button>
      </div>
      <div class="transfer-arrow-row" @click="jiaohuanbtn2">
        <img class="transfer-arrow" src="@/assets/defi/zzn.png" />
      </div>
      <div class="transfer-row">
        <img class="account-icon" :src="transferInAccountList?.icon" />
        <span class="account-title">{{ transferInAccountList?.text }}</span>
        <svg class="dropdown-arrow" @click="showBuyPopup = !showBuyPopup" width="16" height="16" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5" stroke="#bbb" stroke-width="2" fill="none"/></svg>
        <span class="account-balance">{{ _t18('17_transfer2') }}: {{ transgerInAmont && transgerInAmont.amout || 0 }}</span>
      </div>
      <div v-if="showBuyPopup" class="huobi-popup">
        <div class="popup-content">
          <div 
            v-for="(exchange, index) in tempList" 
            :key="index"
            :class="['exchange-option', { selected: transferInAccountList?.text === exchange.text }]"
            @click="selectBuyExchange(exchange)"
          >
            <img :src="exchange.icon" style="width:24px;height:24px;" class="account-icon" />
            <span class="account-title">{{ exchange?.text }}</span>
          </div>
        </div>
      </div>
      <div class="transfer-row" v-if="params.transferInAccount == 9">
        <img class="account-icon" :src="transferxhInAccountList?.loge" />
        <span class="account-title">{{ transferxhInAccountList?.title }}</span>
        <svg class="dropdown-arrow" @click="showxhBuyPopup = !showxhBuyPopup" width="16" height="16" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5" stroke="#bbb" stroke-width="2" fill="none"/></svg>
      </div>
      <!-- ✅ 币种下拉框（现货资产） -->
      <div v-if="showxhBuyPopup" class="huobi-popup">
        <div class="popup-content">
      
          <!-- ✅ 搜索框 -->
          <div class="search-box">
            <input
              v-model="searchCoin"
              class="search-input"
              type="text"
              :placeholder="_t18('search_currency')"
            />
          </div>
      
          <!-- ✅ 币种列表（支持筛选） -->
          <div 
            v-for="(exchange, index) in filteredAssetList" 
            :key="index"
            :class="['exchange-option', { selected: transferxhInAccountList?.icon === exchange.icon }]"
            @click="selectxhBuyExchange(exchange)"
          >
            <div class="exchange-left">
              <img :src="exchange.loge" style="width:24px;height:24px;" class="account-icon" />
              <span class="account-title">{{ exchange?.title }}</span>
            </div>
            <div class="exchange-right">
              <span class="balance">{{ exchange.keyong }}</span>
            </div>
          </div>
		  </div>
      </div>
      <div class="submit-btn-section" @click="submit">
        <button class="submit-btn">{{ _t18('17_transfer1') }}</button>
      </div>
    </div>

    <div class="transfer-bottom-section">
      <div class="transfer-guide-card">
        <div class="guide-title">{{ _t18('17_transfer5') }}</div>
        <div class="guide-content">
          <div class="guide-progress">
            <!-- 保留原 SVG -->
            <svg width="24" height="148" viewBox="0 0 24 148" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="11.5" stroke="#00C693"></circle>
              <circle cx="12" cy="12" r="8" fill="#00C693"></circle>
              <circle cx="12" cy="74" r="11.5" stroke="#00C693"></circle>
              <circle cx="12" cy="74" r="8" fill="#00C693"></circle>
              <circle cx="12" cy="136" r="11.5" fill="#00C693" stroke="#00C693"></circle>
              <line x1="12.5" y1="30.5" x2="12.5" y2="58.5" stroke="#00C693" stroke-linecap="round" stroke-dasharray="2 2"></line>
              <line x1="12.5" y1="92.5" x2="12.5" y2="120.5" stroke="#00C693" stroke-linecap="round" stroke-dasharray="2 2"></line>
              <path d="M9.75012 139.128L6.62262 136L5.55762 137.058L9.75012 141.25L18.7501 132.25L17.6926 131.193L9.75012 139.128Z" fill="white"></path>
            </svg>
          </div>
          <div class="guide-steps">
            <div class="guide-step">{{ _t18('17_transfer6') }}</div>
            <div class="guide-step">{{ _t18('17_transfer7') }}</div>
            <div class="guide-step-last">{{ _t18('17_transfer8') }}</div>
          </div>
        </div>
      </div>

      <div class="transfer-record-card">
        <div class="record-title">{{ _t18('17_transfer9') }}</div>
        <div class="record-list">
          <div class="record-item" v-for="(trans, index) in listArray" :key="index">
            <div class="record-row"><span>{{ _t18('17_transfer10') }}</span><span>USD</span></div>
            <div class="record-row"><span>{{ _t18('17_transfer11') }}</span><span>{{ trans.amount }}</span></div>
            <div class="record-row"><span>{{ _t18('17_transfer12') }}</span><span>{{ typeConfig[trans.transferOutAccount]['name'] }}</span></div>
            <div class="record-row"><span>{{ _t18('17_transfer13') }}</span><span>{{ typeConfig[trans.transferInAccount]['name'] }}</span></div>
            <div class="record-row"><span>{{ _t18('17_transfer14') }}</span><span>{{ formatTo12Hour(trans.createTime) }}</span>
</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { computed, ref, onMounted } from 'vue'
import arrowIcon from '@/assets/defi/zzn.png'
import { useMainStore } from '@/store'
import { useUserStore } from '@/store/user/index'
import { DIFF_ISFREEZE } from '@/config/index'
import { useFreeze } from '@/hook/useFreeze'
import { _t18 } from '@/utils/public'
import { showToast } from 'vant'
import { getTransferList, getUserBalance } from '@/api/account'
import { useToast } from '@/hook/useToast'
import { getTransLog } from '@/api/financial/index'
import { priceFormat, countFormat, currencyFormat } from '@/utils/decimal.js'
import { DIFF_FREEZE_ASSETS } from '@/config/index'

function formatTo12Hour(timeStr) {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  if (isNaN(date)) return timeStr

  let hours = date.getHours()
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  const ampm = hours >= 12 ? 'PM' : 'AM'
  hours = hours % 12
  hours = hours ? hours : 12 // 0 点显示为 12

  const yyyy = date.getFullYear()
  const MM = (date.getMonth() + 1).toString().padStart(2, '0')
  const dd = date.getDate().toString().padStart(2, '0')

  return `${yyyy}-${MM}-${dd} ${hours}:${minutes}:${seconds} ${ampm}`
}

const currentSpotCoin = ref('usdt')
const { _toast } = useToast()
const { _isFreeze } = useFreeze()
const mainStore = useMainStore()
const userStore = useUserStore()
const amount = ref('')
const showBuyPopup = ref(false)
const showxhBuyPopup = ref(false)

 //✅ 搜索框绑定值
const searchCoin = ref('')

// ✅ 计算筛选结果
const filteredAssetList = computed(() => {
  if (!searchCoin.value) return assetDetails.value
  const keyword = searchCoin.value.trim().toLowerCase()
  return assetDetails.value.filter(
    (item) => item.title.toLowerCase().includes(keyword)
  )
})

const params = ref({
  coin: 'usdt',
  transferOutAccount: '',
  transferInAccount: '',
  transferxhInAccount: '',
  amount: ''
})

// 用户余额信息
const { asset } = storeToRefs(userStore)
const assetDetails = computed(() => {
  let list = []
  //[{icon: 'usdt', title: 'USDT', keyong: 100, zhanyong: 100, zhehe: 100}]
  // console.log(asset.value)
  asset.value.forEach((item, index) => {
    // 之前两块多平台判断逻辑是一样的 -> 精简合并

    if (
      (item.type == 9 ) 
    ) {
      let obj = {}
      obj['keyong'] = priceFormat(item.availableAmount)
      // rxce冻结金额=占用+冻结
      if (DIFF_FREEZE_ASSETS.includes(__config._APP_ENV)) {
        let temp = 0
        if (freezeList.value) {
          freezeList.value.forEach((itm, inx) => {
            if (itm.coin == item.symbol && item.type == 1) {
              temp = itm.price
            }
          })
        }
        obj['zhanyong'] = priceFormat(_add(item.occupiedAmount, temp))
      } else {
        obj['zhanyong'] = priceFormat(item.occupiedAmount)
      }
      obj['zhehe'] = priceFormat(item.exchageAmount)
      if (item.symbol == 'usdt') {
        obj['icon'] = 'usdt'
      obj['loge'] = new URL('/static/img/1e8deac3f3e547629a8bf2b466dc0359.png', import.meta.url).href  // ✅ 本地图标
        obj['title'] = 'USDT'
        list.unshift(obj)
      } else {
        obj['loge'] = item.loge
        obj['title'] = item.symbol?.replace('usdt', '').trim().toLocaleUpperCase()
        obj['icon'] = item.symbol?.replace('usdt', '').trim()
        list.push(obj)
      }
    }
  })
  return list
})
console.log(assetDetails.value)
params.value.transferxhInAccount = assetDetails.value[0]?.icon

const transferxhInAccountList = computed(() =>
  assetDetails.value.find((item) => item.icon == params.value.transferxhInAccount)
)

function setAll() {
  params.value.amount = transgerOutAmont.value.amout
}

// 账户icon路径
import a1 from '@/assets/defi/a1.png'
import a2 from '@/assets/defi/a2.png'
import a3 from '@/assets/defi/a3.png'
import a4 from '@/assets/defi/a4.png'
import a5 from '@/assets/defi/a5.png'
import a6 from '@/assets/defi/a6.png'

/* ✅ 所有账户类型国际化 */
const typeConfig = {
  1: { name: _t18('17_transfer15'), icon: a1, color: '#3b5bfd' }, // 平台资产
  2: { name: _t18('17_transfer16'), icon: a2, color: '#7ad1e7' }, // 智能量化帳戶
  3: { name: _t18('17_transfer17'), icon: a3, color: '#b18cff' }, // 合约资产
  4: { name: _t18('17_transfer18'), icon: a4, color: '#ffd86b' }, // 量化合约资产
  5: { name: _t18('17_transfer19'), icon: a5, color: '#ffb1b1' }, // 量化套利资产
  6: { name: _t18('17_transfer20'), icon: a6, color: '#b1c6ff' }, // 期权资产
  7: { name: _t18('17_transfer21'), icon: a6, color: '#b1ffd6' }, // 跟单合约资产
  8: { name: _t18('17_transfer22'), icon: a6, color: '#b2c6ff' }, // AI预测资产
  9: { name: _t18('17_transfer23'), icon: a6, color: '#b1f4d6' }  // 现货资产
}

/* ✅ 动态资产选择 */
const tempList = computed(() => {
  console.log(mainStore.getAssetsTabList)
  const list = mainStore.getAssetsTabList.filter((item) => {
    const key = { 平台资产: 1, 理财资产: 2, 合约资产: 3, 量化合约资产: 4, 量化套利资产: 5, 期权合约资产: 6, 跟单合约资产: 7,现货资产: 9 }
    if (item.value != 2 && item.value != 5 && item.value !=6 && item.value != 7 && item.value != 8) {
      if (!item.isOpen) return false
      if (item.name == '平台资产') item.keyStr = _t18('17_transfer15')
      if (item.name == '理财资产') item.keyStr = _t18('17_transfer16')
      if (item.name == '合约资产') item.keyStr = _t18('17_transfer17')
      if (item.name == '量化合约资产') item.keyStr = _t18('17_transfer18')
      if (item.name == '量化套利资产') item.keyStr = _t18('17_transfer19')
      if (item.name == '期权合约资产') item.keyStr = _t18('17_transfer20')
      if (item.name == '跟单合约资产') item.keyStr = _t18('17_transfer21')
      if (item.name == 'AI预测资产') item.keyStr = _t18('17_transfer22')
      if (item.name == '现货资产') item.keyStr = _t18('17_transfer23')

      item.value = key[item.name]
      item.icon = typeConfig[item.value].icon
      item.text = typeConfig[item.value].name
      return true
    } else {
      return false
    }
    
  })
  console.log(list)
  return list.sort((a, b) => a.sort - b.sort)
})

/* 默认选中第一个账户 */
params.value.transferOutAccount = tempList.value[0]?.value || ''
params.value.transferInAccount = tempList.value[1]?.value || ''

const transferOutAccountList = computed(() =>
  tempList.value.find((item) => item.value == params.value.transferOutAccount)
)
const transferInAccountList = computed(() =>
  tempList.value.find((item) => item.value == params.value.transferInAccount)
)

const transgerOutAmont = computed(() =>
  userStore.userInfo.asset?.find(item => item.symbol === 'usdt' && item.type === params.value.transferOutAccount)
)
const transgerInAmont = computed(() => {
  // 现货资产是 type = 9
  if (params.value.transferInAccount == 9) {
    return userStore.userInfo.asset?.find(
      item => item.symbol?.toLowerCase() === currentSpotCoin.value.toLowerCase() && item.type === 9
    )
  }
  // 非现货时仍然显示USDT
  return userStore.userInfo.asset?.find(
    item => item.symbol?.toLowerCase() === 'usdt' && item.type === params.value.transferInAccount
  )
})


/* ✅ 交换账户 */
const jiaohuanbtn2 = () => {
  [params.value.transferOutAccount, params.value.transferInAccount] = [
    params.value.transferInAccount,
    params.value.transferOutAccount
  ]
  params.value.amount = 0
}

/* ✅ 选择目标账户 */
function selectBuyExchange(exchange) {
  params.value.transferInAccount = exchange.value
  showBuyPopup.value = false
  // if (exchange.value == 9) {
  //   params.value.transferxhInAccount = assetDetails.value[0]?.coin
  // }
}

/* ✅ 选择现货目标账户 */
function selectxhBuyExchange(exchange) {
  params.value.transferxhInAccount = exchange.icon
  currentSpotCoin.value = exchange.icon  // ✅ 更新选中的币种
  showxhBuyPopup.value = false

  // ✅ 找出该币种余额
  const matchAsset = userStore.userInfo.asset?.find(
    item => item.symbol?.toLowerCase() === exchange.icon.toLowerCase() && item.type === 9
  )

  if (matchAsset) {
    exchange.amout = priceFormat(matchAsset.availableAmount)
  } else {
    exchange.amout = 0
  }

  // ✅ 可选：显示 toast 提示
  showToast(`${exchange.title} ${_t18('17_transfer2')}：${exchange.amout}`)
}


/* ✅ 提交表单 */
const submit = () => {
  if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
    if (_isFreeze(DIFF_ISFREEZE)) submitForm()
  } else {
    submitForm()
  }
}

/* ✅ 表单验证 + 提交 */
const submitForm = () => {
  if (params.value.amount == '' || params.value.amount <= 0) {
    return _toast('transfer_please_amount') // 請輸入劃轉金額
  }

  getTransferList(params.value).then((res) => {
    if (res.code == '200') {
      _toast('transfer_success') // 操作成功，請稍後...
      getBalance()
      getInit()
    } else {
      showToast(res.msg || '')
    }
  })
}

/* ✅ 刷新余额 */
const getBalance = async () => {
  userStore.getUserInfo()
}

/* ✅ 获取转账记录 */
const listArray = ref([])
const isShow = ref(false)
const getInit = async () => {
  try {
    const paramsStr = `pageNum=1&pageSize=200&userId=${userStore.userInfo.user?.userId}&orderByColumn=createTime&isAsc=desc`
    const res = await getTransLog(paramsStr)
    if (res.code === 200) {
      listArray.value = res.rows
      listArray.value.length === 0 ? (isShow.value = true) : (isShow.value = false)
    }
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  getInit()
})
</script>


<style scoped>
.transfer-apply-container {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 20px 16px 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}

/* 顶部卡片 */
.transfer-card {
  background: #fff;
  border-radius: 18px;
  padding: 18px 16px 26px;
  width: 100%;
  max-width: 420px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.transfer-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
}

.account-icon {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  margin-right: 8px;
}
.account-title {
  font-size: 15px;
  font-weight: 600;
  color: #111;
  margin-right: auto;
  margin-left: 2px;
}
.account-balance {
  font-size: 13px;
  color: #444;
}

/* 金额输入 */
.transfer-input-row {
  background: #f5f6f8;
  border-radius: 22px;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
}
.transfer-input {
  flex: 1;
  border: none;
  background: transparent;
  border-radius: 22px;
  padding: 12px 18px;
  font-size: 15px;
  color: #111;
  outline: none;
}
.all-btn {
  background: #000;
  color: #fff;
  border: none;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 600;
  padding: 8px 16px;
  margin-right: 10px;
  cursor: pointer;
}

/* 上下切换箭头 */
.transfer-arrow-row {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 12px 0 18px;
}
.transfer-arrow {
  width: 48px;
  height: 48px;
  background: #ff5c5c;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 3px 8px rgba(255,92,92,0.15);
}

/* 下拉选择箭头 */
.dropdown-arrow {
  margin-left: 4px;
}

/* 提交按钮 */
.submit-btn-section {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
.submit-btn {
  width: 100%;
  max-width: 420px;
  height: 50px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 999px;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 1px;
  cursor: pointer;
  transition: all 0.2s;
}
.submit-btn:active {
  background: #222;
}

/* --- 下方说明 --- */
.transfer-bottom-section {
  width: 100%;
  max-width: 420px;
  margin-top: 28px;
}

/* 指南卡片 */
.transfer-guide-card {
  background: #fff;
  border-radius: 18px;
  padding: 20px 18px 22px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.04);
}
.guide-title {
  font-size: 17px;
  font-weight: 700;
  color: #111;
  margin-bottom: 10px;
}
.guide-content {
  display: flex;
  align-items: flex-start;
}
.guide-progress {
  margin-right: 18px;
}
.guide-steps {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 28px;
}
.guide-step,
.guide-step-last {
  font-size: 14px;
  color: #222;
  line-height: 1.6;
}

/* 记录卡片 */
.transfer-record-card {
  background: #fff;
  border-radius: 18px;
  margin-top: 20px;
  padding: 18px 18px 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.04);
}
.record-title {
  font-size: 17px;
  font-weight: 700;
  color: #111;
  margin-bottom: 12px;
}
.record-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.record-item {
  border-top: 1px solid #eee;
  padding-top: 14px;
}
.record-row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #222;
  margin-bottom: 6px;
}
.record-row span:first-child {
  color: #555;
}
.record-row:last-child {
  margin-bottom: 0;
}

/* 弹出框 */
.huobi-popup {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.12);
  max-height: 220px;
  overflow-y: auto;
  padding: 16px 20px;
  width: 100%;
  z-index: 10;
}
.exchange-option {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 6px;
  font-size: 14px;
}
.exchange-option:hover {
  background: #f5f5f5;
}
.exchange-option.selected {
  background: #e8f5e8;
  color: #17AC74;
  font-weight: 600;
  border: 1px solid #17AC74;
}

/* === 修正：轉帳記錄左對齊顯示 === */
.record-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-item {
  border-top: 1px solid #eee;
  padding-top: 13px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

/* 左对齐结构 */
.record-row {
  display: flex;
  justify-content: flex-start; /* ✅ 左对齐 */
  align-items: center;
  gap: 40px; /* 左右列间距 */
  font-size: 13px;
  color: #222;
}

.record-row span:first-child {
  color: #555;
  min-width: 90px; /* 第一列宽度一致 */
  text-align: left;
}

.record-row span:last-child {
  text-align: left;
  flex: 1;
}
.account-amount {
  margin-left: auto;
  font-size: 13px;
  color: #888;
}
.search-box {
  padding: 10px 12px;
  border-bottom: 1px solid #eee;
}

.search-input {
  width: 110%;
  margin-left: -5%;
  padding: 8px 12px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 14px;
  outline: none;
  transition: all 0.2s;
}

.search-input:focus {
  border-color: #17AC74;
  box-shadow: 0 0 4px rgba(23, 172, 116, 0.3);
}

.exchange-option {
  display: flex;
  align-items: center;
  justify-content: space-between; /* ✅ 右侧显示余额 */
  gap: 10px;
  padding: 10px 14px;
  border-radius: 10px;
  cursor: pointer;
  margin-bottom: 6px;
  font-size: 14px;
}

.exchange-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.exchange-right .balance {
  font-size: 13px;
  color: #666;
}

</style>
